// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const subMchId = "1636715260"
const envId = "wjs-4gpwpq5j4372152f"

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContent = cloud.getWXContext() // openid等信息
  const openid = wxContent.OPENID
  const appid = wxContent.APPID

  const {
    id
  } = event

  event.openid = openid

  if (id) {
    return await updateTrade(event)
  }

  return await createNewTrade(event)
}

const createPayment = async (body, outTradeNo, totalFee) => {
  const payment = await cloud.cloudPay.unifiedOrder({
    "body": body,
    "outTradeNo": outTradeNo,
    "spbillCreateIp": "127.0.0.1",
    subMchId, // 商户号
    totalFee, // 分
    envId, // 云环境id
    "functionName": "payCallBack" // 支付回调云函数
  })

  return payment
}

const updateTrade = async (data) => {
  const {
    id
  } = data

  // 读取orders数据
  const res = await db.collection('orders')
    .where({
      _id: id
    }).get()

  const order = res.data[0]

  const {
    totalFee,
  } = order
  const body = '万家顺送水-支付'
  const outTradeNo = createOutTradeNo() // 订单号

  // 获取免鉴权支付参数
  const payMent = await createPayment(body, outTradeNo, totalFee * 100)

  // 更新订单
  const nowTime = new Date().getTime()
  await db.collection('orders')
    .where({
      _id: id
    })
    .update({
      data: {
        updateTime: nowTime,
        outTradeNo: outTradeNo
      }
    })

  return payMent
}

const createNewTrade = async (data) => {
  const {
    body, // 商品名
    totalFee, // 支付金额（单位：分）
    openid,
    remark, // 备注
    goodsList, // 商品列表
    stepFee,
    vipPrice,
    ticketInfo,
    couponInfo,
    deductFeeInfo
  } = data

  const outTradeNo = createOutTradeNo() // 订单号

  // 获取免鉴权支付参数
  const payMent = await createPayment(body, outTradeNo, totalFee)

  // 创建订单
  const curDate = new Date()
  const nowTime = curDate.getTime()
  await addOrder({
    dsName: 'orders',
    _openid: openid,
    outTradeNo,
    totalFee: totalFee * 0.01, // 元
    payStatus: 'wait',
    createTime: nowTime,
    updateTime: nowTime,
    deleteTime: null,
    remark,
    goodsList,
    stepFee,
    vipPrice,
    ticketInfo,
    couponInfo,
    deductFeeInfo,
    status: '待付款'
  })

  return payMent
}

const createOutTradeNo = () => {
  let outTradeNo = new Date().getTime() // 获取当前13位时间戳
  let numStr = '0123456789';
  let randomStr = '';
  for (let i = (32 - 13); i > 0; --i) {
    randomStr += numStr[Math.floor(Math.random() * numStr.length)];
  }
  outTradeNo += randomStr
  return outTradeNo
}

const addOrder = async (orderObj) => {
  const ids = orderObj.goodsList.map(ele => {
    return ele.spuId
  })
  const res = await db.collection('goods')
    .where({
      _id: db.command.in(ids)
    })
    .get()

  orderObj.goodsSnap = res.data
  return await db.collection('orders')
    .add({
      data: orderObj
    })
    .then(res => {
      console.log("创建订单成功", res, orderObj)
    })
    .catch(err => {
      console.log("创建订单异常", err, orderObj)
    })

}